# -*- coding:utf-8 -*-
"""
用户类，定义用户属性与方法
"""
import hashlib
import re


class User:
    """
    @ClassName：User
    @Description： 用户实体类，映射数据库一条用户数据
    负责属性赋值检查，可调用密码加密与效验比对
    @Author：锦沐Python

    参数:
    user_id (str): 学生的 ID
    user_name (str): 用户名
    email (str): 电子邮箱
    role (str): 用户角色 ("user"|"admin")
    password (str): 密码
    account_status (int): 账户状态（0 表示正常，1 表示冻结等）
    create_time (str): 注册时间
    """

    def __init__(self, user_id="", user_name="",
                 email="", role="user", password="",
                 account_status=0, registration_time=""):
        self._user_id = user_id
        self._user_name = user_name
        self._email = email
        self._role = role
        self._password = password
        self._account_status = account_status
        self._registration_time = registration_time

    @property
    def user_id(self):
        return self._user_id

    @user_id.setter
    def user_id(self, user_id):
        if isinstance(user_id, str) and len(user_id) >= 6:
            self._user_id = user_id
        else:
            raise ValueError("user_id 必须是长度至少为 6 的字符串")

    @property
    def user_name(self):
        return self._user_name

    @user_name.setter
    def user_name(self, user_name):
        if isinstance(user_name, str) and len(user_name) > 3:
            self._user_name = user_name
        else:
            raise ValueError("user_name 必须是长度至少为 3 的字符串")

    @property
    def email(self):
        return self._email

    @email.setter
    def email(self, email):
        email_pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
        if isinstance(email, str) and re.match(email_pattern, email):
            self._email = email
        else:
            raise ValueError("email必须是邮箱格式")

    @property
    def role(self):
        return self._role

    @role.setter
    def role(self, role):
        if isinstance(role, str) and (role == "admin" or role == "user"):
            self._role = role
        else:
            raise ValueError("role只能是 user 或 admin")

    @property
    def password(self):
        return self._password

    @password.setter
    def password(self, password):
        if isinstance(password, str) and len(password) >= 6:
            self._password = self.encrypt_password(password)
        else:
            raise ValueError("password 至少是 6 位字符")

    @property
    def account_status(self):
        return self._account_status

    @account_status.setter
    def account_status(self, account_status):
        if isinstance(account_status, int) and (account_status == 1 or account_status == 0):
            self._account_status = account_status
        else:
            raise ValueError("account_status 只能是 0 或 1")

    @property
    def registration_time(self):
        return self._registration_time

    @registration_time.setter
    def registration_time(self, registration_time):
        time_pattern = r'^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$'
        if isinstance(registration_time, str) and re.match(time_pattern, registration_time):
            self._registration_time = registration_time
        else:
            raise ValueError("create_time 时间格式为 2024-07-03 11:10:34")

    def verify_password(self, input_password):
        """
        效验密码
        :param input_password:
        :return:
        """
        hashed_input_password = hashlib.md5(input_password.encode()).hexdigest()
        print(f"{input_password}<---->{hashed_input_password}")
        return self._password == hashed_input_password

    def encrypt_password(self, input_password):
        """
        加密密码
        :param input_password:
        :return:
        """
        hashed_input_password = hashlib.md5(input_password.encode()).hexdigest()
        print(f"{input_password}---->{hashed_input_password}")
        return hashed_input_password

    def obj_to_dict(self):
        # 复制__dict__以避免直接修改实例的属性字典
        user_dict = self.__dict__.copy()
        # 过滤掉不需要序列化的属性（例如，以__开头的Python特殊属性）
        filtered_dict = {k[1:] if k.startswith('_') else k: v for k, v in user_dict.items() if not k.startswith('__')}
        return filtered_dict
